<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Blovex4\Logic;

/**
 * 用户业务逻辑层
 *
 * @author derek <693472824@qq.com>
 */
class UserLogic extends BaseLogic {

    /**
     * 保存用户信息
     * @author derek <693472824@qq.com>
     */
    public function saveAction() {
        
        $userID = I('user_id');
        
        if(empty($userID)){

            $userModel = D('User');
            
            if($userModel->create()){
                return $userModel->add();
            }else{
                $this->error = $userModel->getError();
                return false;
            }
        }else{
            return true;
        }
    }
    
    /**
     * 保存用户维修地址信息
     * @author derek <693472824@qq.com>
     */
    public function saveAddressAction() {
        
        $addressID = I('address_id');
        $addressModel = D('UserAddress');
    
        if ($addressModel->create()) {
    
            if (empty($addressID)) {
                $result = $addressModel->add();
            } else {
                $map['address_id'] = $addressID;
                $result = $addressModel->where($map)->save();
            }
            
            $result = $result === false ? false : (is_numeric($addressID) ? $addressID : $result);
            
            if(is_numeric($result)){
                
                //计算离维修地址最近的站点
                $lat = I('latitude');
                $lng = I('longitude');
                
                $site = M('Site')->field('site_id,ROUND(6378.137*2*ASIN(SQRT(POW(SIN(('.$lat
                        .'*PI()/180-latitude*PI()/180)/2),2)+COS('.$lat.'*PI()/180)*COS(latitude*PI()/180)*POW(SIN(('.$lng
                        .'*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli')->order('juli')->find();
                
                $map['address_id'] = $result;
                $rs = $addressModel->where($map)->setField('site_id', $site['site_id']);
                
                return $result;
            }else{
                return false;
            }
        } else {
            $this->error = $addressModel->getError();
            return false;
        }
    }

}